package com.app.controller;

import com.app.common.*;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.*;
import com.app.util.Result;
import com.app.util.StringTool;
import com.app.util.TokenUtils;
import com.app.vo.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RestController
public class EnterpriseController {
    @Autowired
    EnterpriseService enterpriseService;
    @Autowired
    EnterpriseAlbumService enterpriseAlbumService;
    @Autowired
    ComRecruitersService comRecruitersService;
    @Autowired
    IndustryService industryService;
    @Autowired
    LookMeService lookMeService;
    @Autowired
    UserService userService;

    @Autowired
    private CustomerService customerService;
    @Autowired
    JobPublishService jobPublishService;

    @Autowired
    JobFairCompanyPostService jobFairCompanyPostService;
    @Autowired
    EnterpriseMapper enterpriseMapper;

    @Autowired
    WorkApplyService workApplyService;
    @Autowired
    private JobPublishMapper jobPublishMapper;

    //根据企业名称模糊查询
    @GetMapping("/getEnterpriseName")
    public Result<Object> getEnterpriseName(HttpServletRequest request) {
        String comName = request.getParameter("comName");
        List<EnterpriseModel> modelList = enterpriseService.findAllByName(comName);
        return Result.success(modelList);
    }

    @GetMapping("/getEnterpriseNamePage")
    public Result<Object> getEnterpriseNamePage(HttpServletRequest request, Integer page, Integer limit) {
        String comName = request.getParameter("comName");
        Page<EnterpriseModel> modelPage = enterpriseService.findAllByNamePage(comName, page, limit);
        EnterpriseVo vo = new EnterpriseVo();
        vo.setCount((int) modelPage.getTotal());
        vo.setList(modelPage.getRecords());
        return Result.success(vo);
    }


    //根据登录HR的token查询企业信息
    @GetMapping("/getEnterpriseData")
    public Result<Object> getEnterpriseData(HttpServletRequest request) {
        String token = request.getHeader("token");
        String mobile = TokenUtils.nothingness(token);
        if (mobile == null) {
            return Result.error(405, "token不存在");
        }
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        ComRecruitersModel cus = comRecruitersService.getComRecruitersById(user.getRId());
        EnterpriseModel enterpriseModel = enterpriseService.findModelById(cus.getComId());
        com.alibaba.fastjson.JSONObject json2 = new com.alibaba.fastjson.JSONObject();
        if (enterpriseModel != null) {
            IndustryModel industryModel = industryService.getModelByCode(enterpriseModel.getEnterpriseType());
            json2.put("logoUrl", enterpriseModel.getLogoUrl());
            json2.put("comName", enterpriseModel.getEnterpriseName());
            json2.put("brandName", enterpriseModel.getBrandName());
            json2.put("comType", enterpriseModel.getEnterpriseType());
            if(industryModel!=null)
            {
                json2.put("comTypeText", industryModel.getIndustryName());
            }

            json2.put("financingId", enterpriseModel.getFinancingId());
            json2.put("scaleId", enterpriseModel.getScaleId());
            json2.put("welfare", enterpriseModel.getWelfare());
            json2.put("comIntroduction", enterpriseModel.getEnterpriseIntroduction());
            json2.put("comId", enterpriseModel.getId());
            json2.put("regcap", enterpriseModel.getRegcap());
            json2.put("nature", enterpriseModel.getNature());
            json2.put("enterpriseAddress", enterpriseModel.getEnterpriseAddress());
            json2.put("enterpriseLongitude", enterpriseModel.getEnterpriseLongitude());
            json2.put("enterpriseLatitude", enterpriseModel.getEnterpriseLatitude());
            json2.put("isStateOwned", enterpriseModel.getIsStateOwned());//国有
            json2.put("isDomesticInvestment", enterpriseModel.getIsDomesticInvestment());//内资
            json2.put("isGoOnTheMarket", enterpriseModel.getIsGoOnTheMarket());//上市
            json2.put("streetId",enterpriseModel.getStreetId());
            List<EnterpriseAlbumModel> imgList = enterpriseAlbumService.getListByComId(enterpriseModel.getId());
            if (imgList == null) {
                json2.put("imgUrlList", "");
            } else {
                json2.put("imgUrlList", imgList);
            }
        }
        return Result.success(json2);
    }

    //根据登录HR的token查询企业信息
    @PostMapping("/updateEnterprise")
    public Result<Object> updateEnterprise(HttpServletRequest request,
                                           @RequestParam(required = false) String logoUrl,
                                           String brandName,
                                           String comType, String regcap,
                                           Integer scaleId, String comIntroduction, String imgUrlList,
                                           @RequestParam(required = false) String welfare,
                                           Integer nature,Integer streetId,
                                           String enterpriseAddress, double enterpriseLongitude, double enterpriseLatitude
    ) {
        String token = request.getHeader("token");
        String mobile = TokenUtils.nothingness(token);
        if (mobile == null) {
            return Result.error(405, "token不存在");
        }
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        ComRecruitersModel cus = comRecruitersService.getComRecruitersById(user.getRId());
        EnterpriseModel model = enterpriseService.findModelById(cus.getComId());
        if(StringTool.isNotEmpty(logoUrl))
        {
            model.setLogoUrl(logoUrl);
        }else {
            model.setLogoUrl("https://www.mashangjiuye.cn/file/91885/img/enterprise.png");
        }

        model.setBrandName(brandName);
        model.setEnterpriseType(comType);
        model.setStreetId(streetId);
        model.setRegcap(regcap);
        model.setScaleId(scaleId);
        model.setEnterpriseIntroduction(comIntroduction);
        model.setWelfare(welfare);
        model.setNature(nature);
        model.setEnterpriseAddress(enterpriseAddress);
        model.setEnterpriseLongitude(enterpriseLongitude);
        model.setEnterpriseLatitude(enterpriseLatitude);
        enterpriseService.update(model);
        if (imgUrlList != null && imgUrlList != "") {
            String str[] = imgUrlList.split(",");
            for (int i = 0; i < str.length; i++) {
                EnterpriseAlbumModel album = new EnterpriseAlbumModel();
                album.setComId(model.getId());
                album.setImgUrl(str[i]);
                enterpriseAlbumService.insert(album);
            }
        }
        return Result.success(null);
    }

    //查询全部企业以及岗位
    @GetMapping("/getEnterpriseAll")//根据开放的岗位的公司和名字模糊查询的公司进行比较 取重复的
    public Result<Object> getEnterpriseAll(HttpServletRequest request) {
        String comName = (request.getParameter("comName"));
        JobPublishModel model = new JobPublishModel();
        EnterpriseModel enterpriseModel = new EnterpriseModel();

        model.setRecruitState(3);
        List<JobPublishModel> jobPublishModelList = jobPublishService.getJobPublishListByModel(model);
        List<EnterpriseModel> enterpriseModelList = new ArrayList<>();
        for (int i = 0; i < jobPublishModelList.size(); i++) {

            enterpriseModel = enterpriseService.findLogoById(jobPublishModelList.get(i).getEnrollId());
            enterpriseModelList.add(enterpriseModel);
        }
        List<EnterpriseModel> enterpriseModel2 = new ArrayList<>();
        enterpriseModel2 = enterpriseService.findModelByName(comName);
        if (enterpriseModel2 == null) {
            return Result.success(null);
        }
//        enterpriseModelList.retainAll(enterpriseModel2);
        enterpriseModel2.retainAll(enterpriseModelList);
        if (enterpriseModelList == null) {
            return Result.success(null);
        }
//        HashSet set = new HashSet(enterpriseModelList);
//        enterpriseModelList.clear();
//        //把HashSet对象添加至List集合
//        enterpriseModelList.addAll(set);

        return Result.success(enterpriseModel2);
    }

    //根据ID查询企业信息
    @GetMapping("/getEnterpriseById")
    public Result<Object> getEnterpriseById(HttpServletRequest request,
                                            @RequestParam(required = false) Integer id,@RequestParam(required = false) Integer isDp
    ) {
        String token = request.getHeader("token");
        UserModel user = null;
        CustomerModel cus = null;
        if (token != null) {
            String mobile = TokenUtils.nothingness(token);
            user = userService.getUserByMobile(mobile);
            cus = customerService.getCustomerById(user.getCId());
        }

        if (id != null && id > 0) {
            EnterpriseModel enterpriseModel = enterpriseService.findModelById(id);
            if(enterpriseModel==null)
            {
                return Result.success(null);
            }
            String str[] = {String.valueOf(id)};
            List<ComRecruitersModel> comRecruitersModelList = comRecruitersService.getComRecruitersByComId(str);
            if(comRecruitersModelList!=null&&comRecruitersModelList.size()>0)
            {
                enterpriseModel.setHrName(comRecruitersModelList.get(0).getRealName());
                UserModel userModel = userService.getUserByRId(comRecruitersModelList.get(0).getId());
                enterpriseModel.setHrMobile(userModel.getMobile());
            }
            List<EnterpriseAlbumModel> enterpriseAlbumModel = enterpriseAlbumService.getListByComId(enterpriseModel.getId());
            enterpriseModel.setAlbumModelList(enterpriseAlbumModel);
            ScaleVo scaleVo = new ScaleVo();
            for (int i = 0; i < ScaleTool.SCALE_VO_LIST.size(); i++) {
                if (enterpriseModel.getScaleId() != null && ScaleTool.SCALE_VO_LIST.get(i).getId() == enterpriseModel.getScaleId()) {
                    scaleVo = ScaleTool.SCALE_VO_LIST.get(i);
                }
            }
            enterpriseModel.setScaleVo(scaleVo);
            enterpriseModel.setScaleName(scaleVo.getData());
            IndustryModel industryModel = industryService.getModelByCode(enterpriseModel.getEnterpriseType());
            enterpriseModel.setEnterpriseTypeText(industryModel.getIndustryName());
            if (enterpriseModel.getNature() != null) {
                enterpriseModel.setNatureText(NatureTool.myMap.get(enterpriseModel.getNature()));
            }
            if (cus != null) {
                LookMeModel lookMe2 = lookMeService.findRidAndPid(0, 0, enterpriseModel.getId(), cus.getId(), 1, 2);//查询关注状态
                if (lookMe2 != null) {
                    enterpriseModel.setFollow(1);
                } else {
                    enterpriseModel.setFollow(0);
                }
            }
            JobPublishModel jobPublishModel = new JobPublishModel();
            jobPublishModel.setEnrollId(id);
            if(isDp==null)
            {
                jobPublishModel.setRecruitState(3);
            }
            List<JobPublishModel> jobPublishList = jobPublishService.getJobPublishListByModel(jobPublishModel);
            if (jobPublishList != null && jobPublishList.size() > 0) {
                for (JobPublishModel publishModel : jobPublishList) {
                    Integer resumeCount = workApplyService.getWorkApplyCountByPublishId(publishModel.getId());
                    publishModel.setResumeCount(resumeCount);
                    int expId = publishModel.getExpId();
                    int eduId = publishModel.getEduId();
                    for (int j = 0; j < ExperienceTool.EXPERIENCE_VO_LIST.size(); j++) {
                        if (expId == ExperienceTool.EXPERIENCE_VO_LIST.get(j).getId()) {
                            if (expId == 1 || expId == 6) {
                                publishModel.setExpRequireText(ExperienceTool.EXPERIENCE_VO_LIST.get(j).getData());
                            } else {
                                publishModel.setExpRequireText(ExperienceTool.EXPERIENCE_VO_LIST.get(j).getData() + "年");
                            }
                        }
                    }
                    for (int j = 0; j < EducationTool.EDUCATION_VO_LIST.size(); j++) {
                        if (eduId == EducationTool.EDUCATION_VO_LIST.get(j).getId()) {
                            publishModel.setMinEducationText(EducationTool.EDUCATION_VO_LIST.get(j).getData());
                        }
                    }
                }
            }
            enterpriseModel.setJobPublishList(jobPublishList);
            return Result.success(enterpriseModel);
        } else {
            return Result.error(500, "ID不存在");
        }

    }

    /**
     * 重点企业统计
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/getKeynoteList")
    public Result<Object> getKeynoteList(Integer page, Integer limit) {
        EnterpriseModel ent = new EnterpriseModel();
        ent.setPage((page - 1) * limit);
        ent.setLimit(limit);
        List<EnterpriseModel> enterpriseList = enterpriseMapper.getKeynotePage(ent);
        KeynoteEntListVo vo = new KeynoteEntListVo();
        List<KeynoteEntVo> list = new ArrayList<>();
        for (EnterpriseModel enterpriseModel : enterpriseList) {
            KeynoteEntVo keynoteEntVo = new KeynoteEntVo();
            keynoteEntVo.setId(enterpriseModel.getId());
            keynoteEntVo.setEntName(enterpriseModel.getEnterpriseName());
            int jobCount = jobPublishService.getJobPublishCountByComId(enterpriseModel.getId());
            keynoteEntVo.setDemandCount(jobCount);
            int jobNumber = jobPublishService.sumJobNumberByEntId(enterpriseModel.getId());
            keynoteEntVo.setDeliver(jobNumber);
            int gap = workApplyService.enterpriseWorkApplyCount(enterpriseModel.getId());
            keynoteEntVo.setGap(gap);
            if(jobNumber > 0)
            {
                int few = jobNumber - gap;
                if(few<0)
                {
                    few = 0;
                }
                double proportion = Math.rint(((double) few / (double) jobNumber)*100);
                keynoteEntVo.setProportion(proportion);
            }else{
                keynoteEntVo.setProportion(0);
            }
            list.add(keynoteEntVo);
        }
        int jobCounts = jobPublishMapper.selectJobCount();
        vo.setJobCount(jobCounts);
        vo.setList(list);
        vo.setCount(enterpriseMapper.getKeynoteCount());
        return Result.success(vo);
    }

    //根据ID查询企业的开放岗位信息
    @GetMapping("/getEnterprisePubById")
    public Result<Object> getEnterprisePubById(HttpServletRequest request,
                                               @RequestParam(required = false) Integer comId
    ) {
        String token = request.getHeader("token");
        String mobile = TokenUtils.nothingness(token);
        if (mobile == null) {
            return Result.error(405, "token不存在");
        }

        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        CustomerModel cus = customerService.getCustomerById(user.getCId());
        JobPublishModel model = new JobPublishModel();
        EnterpriseModel enterpriseModel = new EnterpriseModel();

        model.setEnrollId(comId);
        model.setRecruitState(3);
        if (comId != null && comId > 0) {
            List<JobPublishModel> jobPublishModelList = jobPublishService.findJobPublishListByModel(model);
            EnterpriseModel enterprise = enterpriseService.findModelById(comId);
            if (enterprise.getWelfare() != null && enterprise.getWelfare() != "") {


                for (int i = 0; i < jobPublishModelList.size(); i++) {
                    if (StringTool.isNotEmpty(jobPublishModelList.get(i).getWelfare())) {
                        String[] welfareStr = jobPublishModelList.get(i).getWelfare().split(",");
                        List<ExperienceVo> pubWelfareList = new ArrayList<>();
                        for (int j = 0; j < welfareStr.length; j++) {
                            for (int k = 0; k < WelfareTool.SKILL_VO_LIST.size(); k++) {
                                if (WelfareTool.SKILL_VO_LIST.get(k).getData().equals(welfareStr[j])) {
                                    pubWelfareList.add(WelfareTool.SKILL_VO_LIST.get(k));
                                }
                            }
                        }
                        jobPublishModelList.get(i).setWelfareList(pubWelfareList);
                    }

                }
            } else {
                for (int i = 0; i < jobPublishModelList.size(); i++) {
                    jobPublishModelList.get(i).setWelfare(null);
                }
            }
            return Result.success(jobPublishModelList);
        } else {
            return Result.error(500, "ID不存在");
        }

    }

    @GetMapping("/getEnterpriseList")
    public Result<Object> getEnterpriseList(Integer page, Integer limit,Integer scaleId,String industryId) {
        EnterpriseModel model = new EnterpriseModel();
        model.setPage(page);
        model.setLimit(limit);
        model.setScaleId(scaleId);
        model.setEnterpriseType(industryId);
        List<EnterpriseModel> modelList = enterpriseService.findModelAll(model);
        for (int i = 0; i < modelList.size(); i++) {
            int fairCount = jobPublishService.getModelCountByEid(modelList.get(i).getId());
            modelList.get(i).setFairCount(fairCount);
            modelList.get(i).setScaleName("暂无规模");
            for (int j = 0; j < ScaleTool.SCALE_VO_LIST.size(); j++) {
                if (modelList.get(i).getScaleId() != null && modelList.get(i).getScaleId() == ScaleTool.SCALE_VO_LIST.get(j).getId()) {
                    modelList.get(i).setScaleName(ScaleTool.SCALE_VO_LIST.get(j).getData());
                }
            }

            if(StringTool.isNotEmpty(modelList.get(i).getEnterpriseType()))
            {
                IndustryModel industryModel = industryService.getModelByCode(modelList.get(i).getEnterpriseType());
                if(industryModel!=null)
                {
                    modelList.get(i).setEnterpriseName(industryModel.getIndustryName());
                }

            }else{
                modelList.get(i).setEnterpriseName("暂无行业");
            }

        }

        EnterpriseVo vo = new EnterpriseVo();
        vo.setList(modelList);
        vo.setCount(enterpriseMapper.getComPopularCount(model));
        return Result.success(vo);
    }

    @Autowired
    HandleEnterpriseMapper handleEnterpriseMapper;
    @PostMapping("/handleEnterpriseList")
    public Result<Object> handleEnterpriseList() {
        List<HandleEnterpriseModel> list = handleEnterpriseMapper.selectList(null);
        for (HandleEnterpriseModel handleEnterpriseModel : list) {
            EnterpriseModel enterpriseModel = enterpriseService.findAllByName(handleEnterpriseModel.getName()).get(0);
            String da = handleEnterpriseModel.getType();
            if(StringTool.isNotEmpty(da))
            {
                String str1 = da.substring(0, da.indexOf("|"));
                String str2=da.substring(str1.length()+1);
                IndustryModel industryModel = industryService.getModelByName(str2.trim());
                if(industryModel!=null)
                {
                    enterpriseModel.setEnterpriseType(industryModel.getIndustryCode());
                    enterpriseService.update(enterpriseModel);
                }
            }
        }
        return Result.success("操作成功");
    }


    @PostMapping("/handleEnterpriseNature")
    public Result<Object> handleEnterpriseNature() {
        List<HandleEnterpriseModel> list = handleEnterpriseMapper.selectList(null);
        for (HandleEnterpriseModel handleEnterpriseModel : list) {
            EnterpriseModel enterpriseModel = enterpriseService.findAllByName(handleEnterpriseModel.getName()).get(0);
            if(handleEnterpriseModel.getNature().contains("一人") || handleEnterpriseModel.getNature().contains("个人"))
            {
                enterpriseModel.setNature(11);
            }
            if(handleEnterpriseModel.getNature().contains("股份")||handleEnterpriseModel.getNature().contains("集团"))
            {
                enterpriseModel.setNature(3);
            }
            if((handleEnterpriseModel.getNature().contains("有限")||handleEnterpriseModel.getNature().contains("内资"))&&!handleEnterpriseModel.getNature().contains("股份"))
            {
                enterpriseModel.setNature(4);
            }
            if(handleEnterpriseModel.getNature().contains("全民")||handleEnterpriseModel.getNature().contains("集体"))
            {
                enterpriseModel.setNature(12);
            }
            if(handleEnterpriseModel.getNature().contains("全民")||handleEnterpriseModel.getNature().contains("集体"))
            {
                enterpriseModel.setNature(12);
            }
            if(handleEnterpriseModel.getNature().contains("合作社"))
            {
                enterpriseModel.setNature(14);
            }
            if(handleEnterpriseModel.getNature().contains("国有")||handleEnterpriseModel.getNature().contains("事业"))
            {
                enterpriseModel.setNature(8);
            }
            if(handleEnterpriseModel.getNature().contains("国有"))
            {
                enterpriseModel.setIsStateOwned(1);
            }
            if(handleEnterpriseModel.getNature().contains("内资"))
            {
                enterpriseModel.setIsDomesticInvestment(1);
            }
            if(handleEnterpriseModel.getNature().contains("上市"))
            {
                enterpriseModel.setIsGoOnTheMarket(1);
            }
            enterpriseService.update(enterpriseModel);
        }
        return Result.success("操作成功");
    }



}